package searchservicelogic

import (
	"center-data-platform/app/search/rpc/model"
	"context"
	"encoding/json"

	"center-data-platform/app/search/rpc/internal/svc"
	"center-data-platform/app/search/rpc/search"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchLogic {
	return &SearchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchLogic) Search(in *search.SearchReq) (*search.SearchResp, error) {
	query, err := l.svcCtx.EsBuilder.
		SetSize(in.PageSize).
		SetPage(in.Page).
		SetSimpleQueryString(in.Keyword, []string{"title", "content"}).
		Build()
	if err != nil {
		return nil, err
	}
	res, err := l.svcCtx.ElasticSearch.Search("post", query)
	if err != nil {
		return nil, err
	}
	var posts model.Post
	var resp []*search.PostDetail
	if err = json.NewDecoder(res.Body).Decode(&posts); err != nil {
		return nil, err
	}
	data := posts.Hits.Hits
	for _, v := range data {
		resp = append(resp, &search.PostDetail{
			Id:          int64(v.Source.Id),
			UserId:      int64(v.Source.UserId),
			Type:        int64(v.Source.Type),
			Title:       v.Source.Title,
			Content:     v.Source.Content,
			Cover:       v.Source.Cover,
			FileIds:     v.Source.FileIds,
			Description: v.Source.Description,
			Tags:        v.Source.Tags,
			CreatedAt:   v.Source.CreatedTime,
			UpdatedAt:   v.Source.UpdatedTime,
			Status:      int64(v.Source.Status),
		})
	}
	return &search.SearchResp{
		Data: resp,
	}, nil
}
